package com.bjc.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @program: nettypro
 * @description:
 * @author: bjc
 * @create: 2021-09-04 21:42
 */
public class GroupChatServer {

    private Selector selector;

    private ServerSocketChannel listenChannel;

    private static final int PORT = 6667;

    public GroupChatServer() {
        try {
            //得到选择器
            selector = Selector.open();
            //ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            listenChannel.configureBlocking(false);
            //将该listenChannel 注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听事件
     */
    public void listen(){
        System.out.println("监听线程"+Thread.currentThread().getName());
        try {
            while (true){
//                int count = selector.select(2000L);
                int count = selector.select();
                //有事件发生
                if (count>0){
                    //获取selectionKey集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        //取出selectionKey
                        SelectionKey key = iterator.next();
                        //监听到accept
                        if (key.isAcceptable()){
                            SocketChannel sc = listenChannel.accept();
                            //设置为非阻塞
                            sc.configureBlocking(false);
                            //将该sc 注册到seletor
                            sc.register(selector,SelectionKey.OP_READ);
                            //提示
                            System.out.println(sc.getRemoteAddress()+"上线");
                        }
                        //通道发生read事件  即通道是可读的状态
                        if (key.isReadable()){
                            //处理读
                            readData(key);
                        }
                        //当前的key删除，防止重复操作这个key
                        iterator.remove();
                    }
                }
            }
        } catch (ClosedChannelException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取客户端消息
     *
     * @param key
     */
    public void readData(SelectionKey key) {
        //获取到关联的channel
        SocketChannel channel = null;

        try {
            //得到channel
            channel = (SocketChannel) key.channel();
            //创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            //根据count的值做处理
            if (count>0){
                //把缓存区的数据转成字符串
                String msg = new String(buffer.array());
                //输出该消息
                System.out.println("from 客户端："+msg);
                //向其他的客户端转发消息(要排除自己)
                sendInfoToOtherClients(msg,channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress()+"离线了");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 转发消息给其他客户端（通道）
     * @param msg
     * @param self
     */
    public void sendInfoToOtherClients(String msg,SocketChannel self) throws IOException {
        System.out.println("服务器接收消息中。。。");
        System.out.println("服务器转发数据给客户端线程："+Thread.currentThread().getName());
        //遍历所有注册到selector上的SocketChannel，并排除self（自己）
        selector.keys().forEach(key->{
            //通过key取出对应的SocketChannel
            Channel targetChannel = key.channel();
            //排除自己
            if (targetChannel instanceof SocketChannel && targetChannel!= self){
                SocketChannel dest = (SocketChannel) targetChannel;
                //将msg存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                //将buffer的数据写入到通道
                try {
                    dest.write(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static void main(String[] args) {
        GroupChatServer groupServer = new GroupChatServer();
        groupServer.listen();
    }
}
